class RutgerFlickrPlugin < Liquid::Block

require 'rexml/document'
require 'open-uri'
require 'cgi'

def initialize(tag_name, markup, tokens)
    super

    @attributes = {
      :userid => '83016959@N00',
      :count => 6
      }
      
    markup.scan(Liquid::TagAttributes) do |key, value|
      @attributes[key.to_sym] = value
    end
end

def user_id
  @attributes[:userid]
end

def count
  @attributes[:count]
end

def render(context)
    result = []
    photos = search({"user_id",user_id,"per_page",count})
    photos.each do |pic|
      context.stack do
        context['photo'] = pic
        result << render_all(@nodelist, context)
      end
    end

    result
end

def request(method, arguments={})

  endpoint = "http://api.flickr.com/services/rest/"
  arg_map = arguments.collect {|arg,value| CGI.escape(arg)+"="+CGI.escape(value.to_s)}.join("&")
  call_uri = "#{endpoint}?api_key=#{Mephisto::Plugin[:rutger_flickr_plugin].api_key}&method=#{method}&#{arg_map}"
  
  response = REXML::Document.new(open(call_uri).read)
  if response.root.attributes["stat"] == "ok" then
    return response
  elsif response.root.attributes["stat"] == "fail" then
    raise "Flickr API error #{response.elements["rsp/err"].attributes["code"]}: #{response.elements["rsp/err"].attributes["msg"]}"
  else
    raise "Request status neither ok nor fail. Tried to fetch #{call_uri}."
  end
end

def search(arguments={})
  
  response = request("flickr.people.getPublicPhotos",arguments)
  
  #photo_ids = REXML::XPath.match(response, "//photo/attribute::id").collect { |a| Photo.new(a.value) }
  photos = REXML::XPath.match(response, "//photo").collect { |item| Photo.new(item.attributes["secret"], item.attributes["id"], item.attributes["farm"], item.attributes["server"], item.attributes["owner"]) }  
  
end

class Photo < Liquid::Drop
  
  def initialize(secret = "0", id="0", farm="0", server="0", userid="0")
    @secret = secret
    @id = id
    @farm = farm
    @server = server
    @userid = userid
  end
  
  attr_reader :secret, :id, :farm, :server, :userid
  
end

end